package com.sinogrand.elevator.network

import android.content.Context
import android.util.Log
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.StringUtils
import com.sinogrand.elevator.utils.TokenManager
import com.sinogrand.elevator.utils.EnvironmentManager
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import java.io.IOException
import com.google.gson.JsonParser
import com.sinogrand.elevator.utils.AuthStateManager

/**
 * 网络客户端配置
 */
object NetworkClient {
    
    private var retrofit: Retrofit? = null
    
    fun getApiService(context: Context): ApiService {
        // 每次都重新创建Retrofit实例以支持环境切换
        retrofit = createRetrofit(context)
        return retrofit!!.create(ApiService::class.java)
    }
    
    private fun createRetrofit(context: Context): Retrofit {
        val tokenManager = TokenManager(context)
        val environmentManager = EnvironmentManager(context)
        
        // 获取当前环境的API基础URL
        val baseUrl = environmentManager.getCurrentBaseUrl()
        Log.i(LogTags.NETWORK, "🌐 使用API地址: $baseUrl")
        
        val httpClient = OkHttpClient.Builder()
            .addInterceptor(LoggingInterceptor(tokenManager))
            .addInterceptor(AuthInterceptor(tokenManager))
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()
        
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(httpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
    
    /**
     * 清除缓存的Retrofit实例，强制重新创建
     */
    fun clearCache() {
        retrofit = null
        Log.i(LogTags.NETWORK, "🧹 网络客户端缓存已清除")
    }
}

/**
 * 日志拦截器 - 记录简洁的请求和响应信息，并处理401错误
 */
class LoggingInterceptor(private val tokenManager: TokenManager) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val startTime = System.currentTimeMillis()
        
        // 获取请求信息
        val url = request.url.toString()
        val method = request.method
        val requestBody = getRequestBody(request)
        
        val response: Response
        try {
            response = chain.proceed(request)
            val endTime = System.currentTimeMillis()
            val duration = endTime - startTime
            
            // 获取响应信息
            val responseBody = getResponseBody(response)
            val isSuccess = response.isSuccessful
            val statusCode = response.code
            val statusMessage = response.message
            
            // 检查401错误
            check401Error(responseBody)
            
            // 输出单条日志
            val logMessage = buildLogMessage(
                method = method,
                url = url,
                requestBody = requestBody,
                statusCode = statusCode,
                statusMessage = statusMessage,
                responseBody = responseBody,
                duration = duration,
                isSuccess = isSuccess
            )
            
            if (isSuccess) {
                Log.i(LogTags.NETWORK, logMessage)
            } else {
                Log.e(LogTags.NETWORK, logMessage)
            }
            
        } catch (e: IOException) {
            val endTime = System.currentTimeMillis()
            val duration = endTime - startTime
            
            // 输出错误日志
            val errorMessage = buildErrorLogMessage(
                method = method,
                url = url,
                requestBody = requestBody,
                error = e,
                duration = duration
            )
            
            Log.e(LogTags.NETWORK, errorMessage)
            throw e
        }
        
        return response
    }
    
    private fun getRequestBody(request: okhttp3.Request): String {
        return if (request.body != null) {
            try {
                val buffer = okio.Buffer()
                request.body!!.writeTo(buffer)
                buffer.readUtf8()
            } catch (e: Exception) {
                "无法读取请求体: ${e.message}"
            }
        } else {
            "无请求体"
        }
    }
    
    private fun getResponseBody(response: Response): String {
        return if (response.body != null) {
            try {
                val source = response.body!!.source()
                source.request(Long.MAX_VALUE)
                val buffer = source.buffer
                buffer.clone().readUtf8()
            } catch (e: Exception) {
                "无法读取响应体: ${e.message}"
            }
        } else {
            "无响应体"
        }
    }
    
    private fun check401Error(responseBody: String) {
        try {
            val jsonObject = JsonParser.parseString(responseBody).asJsonObject
            val code = jsonObject.get("code")?.asInt
            
            if (code == 401) {
                Log.w(LogTags.NETWORK, "🔒 检测到401错误，执行强制退出登录")
                // 使用全局认证状态管理器
                AuthStateManager.forceLogout("401未授权错误")
            }
        } catch (e: Exception) {
            // 忽略JSON解析错误
        }
    }
    
    private fun buildLogMessage(
        method: String,
        url: String,
        requestBody: String,
        statusCode: Int,
        statusMessage: String,
        responseBody: String,
        duration: Long,
        isSuccess: Boolean
    ): String {
        val status = if (isSuccess) "✅" else "❌"
        val color = if (isSuccess) "🟢" else "🔴"
        
        return buildString {
            appendLine("$color $status [$method] $url")
            appendLine("📤 请求:")
            appendLine(StringUtils.formatString(requestBody))
            appendLine("📥 响应:")
            appendLine(StringUtils.formatString(responseBody))
            appendLine("⏱️ 耗时: ${duration}ms | 状态: $statusCode $statusMessage")
        }
    }
    
    private fun buildErrorLogMessage(
        method: String,
        url: String,
        requestBody: String,
        error: IOException,
        duration: Long
    ): String {
        return buildString {
            appendLine("🔴 ❌ [$method] $url")
            appendLine("📤 请求:")
            appendLine(StringUtils.formatString(requestBody))
            appendLine("💥 错误: ${error.javaClass.simpleName} - ${error.message}")
            appendLine("⏱️ 耗时: ${duration}ms")
        }
    }
}

/**
 * 认证拦截器 - 添加Authorization头
 */
class AuthInterceptor(private val tokenManager: TokenManager) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val token = tokenManager.getToken()
        
        val newRequest = if (token.isNotEmpty()) {
            Log.d(LogTags.NETWORK, "添加Authorization头: $token")
            originalRequest.newBuilder()
                .addHeader("Authorization", token)
                .build()
        } else {
            Log.d(LogTags.NETWORK, "无token，跳过Authorization头")
            originalRequest
        }
        
        return chain.proceed(newRequest)
    }
}